<template>
  <!-- 导航栏 -->
  <van-nav-bar title="购物车" left-text="返回" left-arrow fixed placeholder z-index="1000" @click-left="back" />
  
  <!-- 下拉刷新 -->
  <van-pull-refresh v-model="refreshing" @refresh="OnRefresh">
      <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="OnLoad"
      >
          <van-checkbox-group ref="CheckboxGroup" v-model="CheckedArr" @change="OnToggleGroup">
              <div class="cart" v-for="(item, index) in CartList" :key="item.id">
                  <van-checkbox :name="item.id"></van-checkbox>

                  <!-- 滑动单元格 -->
                  <van-swipe-cell>
                      <!-- 商品卡片 -->
                      <van-card
                          :thumb="item.product.thumb_text"
                          @click-thumb="ToProductInfo(item.product.id)"
                      >
                          <template #title>
                              <div class="title">{{item.product.name}}</div>
                          </template>
                          
                          <!-- 商品规格 -->
                          <template #desc v-if="item.attrs">
                              <van-tag v-for="(attr, index) in item.attrs" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
                          </template>
                          <template #desc v-else>
                              <van-tag class="tag" type="danger">无规格</van-tag>
                          </template>

                          <template #tags>
                              <div class="price">单价：￥{{ item.price }}</div>
                          </template>

                          <template #price>
                              <div class="price">合计：￥{{ item.total }}</div>
                          </template>

                          <!-- 步进器 -->
                          <template #num>
                              <van-stepper v-model="item.nums" :name="index" :integer="true" :disable-input="true" @change="OnCartUpdate" />
                          </template>
                      </van-card>

                      <!-- 滑动单元格插槽 右侧滑动 -->
                      <template #right>
                          <van-button
                              square
                              text="删除"
                              type="danger"
                              class="delete-button"
                              @click="OnDel(item,index)"
                          />
                      </template>
                  </van-swipe-cell>
              </div>
          </van-checkbox-group>

      </van-list>
  </van-pull-refresh>

  <!-- 提交动作栏 -->
  <van-submit-bar :price="total" button-text="提交订单" @submit="OnSubmit">
      <van-checkbox v-model="CheckedAll" :indeterminate="IsIndeterminate" @change="OnToggle">全选</van-checkbox>
  </van-submit-bar>
</template>

<script setup>

  const { proxy } = getCurrentInstance()

  let business = proxy.$business
  const CartList = ref([]);
  const refreshing = ref(false);
  const finished = ref(false);
  const loading = ref(false);
  const page = ref(1);

  const CheckedArr = ref([]); //当前选中
  const CheckedAll = ref(false); //是否全部选中
  const CheckboxGroup = ref(null); //底部全选和反选
  const IsIndeterminate = ref(false); //底部提交栏复选框状态
  

  //计算属性用于计算总价
  const total = computed(() => {
      let total = 0

      CartList.value.map(item => {
          //判断id 是否在勾选的数组内 在的话就叠加价格
          if(CheckedArr.value.includes(item.id))
          {
              total += parseFloat(item.total)
          }
      })

      return parseFloat(total * 100) //转换为分
  })

  // 跳转商品详情
  const ToProductInfo = (proid) => proxy.$router.push({path: '/product/info', query: {proid}})

  //返回上一页
  const back = () => proxy.$router.push('/')

  //下拉刷新的方法
  const OnRefresh = () => 
  {
      // 清空查询参数
      finished.value = false;
      page.value = 1;
      CartList.value = [];
      loading.value = true;

      // 加载数据方法
      setTimeout(OnLoad, 1500);
  }

  //上拉加载数据
  const OnLoad = async () => 
  {
      // 如果等于true说明当前进行下拉刷新
      if(refreshing.value)
      {
          // 结束下拉刷新
          refreshing.value = false;
      }

      //组装数据
      let params = {
          busid: business.value.id,
          page: page.value
      }

      var result = await proxy.$POST({url: '/cart/index', params})

      if(result.code == 0)
      {
          proxy.$fail(result.msg)

          finished.value = true //没有更多数据
      }
      
      CartList.value = CartList.value.concat(result.data.list)

      let count = result.data.count //购物车总数量

      //循环遍历，将规格的json信息变成js对象
      CartList.value.map(item => item.attrs = JSON.parse(item.attrs))

      // 如果没有更多数据了，就说明已经加载到底了
      if(CartList.value.length >= count)
      {
          finished.value = true
          return false
      }

      page.value = page.value + 1
  }

  //单个复选框切换
  const OnToggleGroup = () =>
  {
      //全部选中判断
      CheckedAll.value = CheckedArr.value.length == CartList.value.length

      //部分选中 只有选择部分内容才是true 如果全部选中和全部未选中都是false
      IsIndeterminate.value = CheckedArr.value.length > 0 && CheckedArr.value.length < CartList.value.length
  }

  // 底部全选和反选
  const OnToggle = () => CheckboxGroup.value.toggleAll()

  //购物车数量更新
  const OnCartUpdate = async (value, {name}) => 
  {
      // value -> 数量
      let cartid = CartList.value[name].id ? CartList.value[name].id : 0
      
      //组装数据
      var params = {
          cartid,
          busid: business.value.id,
          nums: value
      }

      var result = await proxy.$POST({url: '/cart/edit', params})

      if(result.code == 0)
      {
          proxy.$fail(result.msg)
          return false
      }

      //更改一下产品小计 total
      CartList.value[name].total = (parseFloat(CartList.value[name].price * value)).toFixed(2)
  }

  //删除购物车记录
  const OnDel = async (item, index) =>
  {
      //确认对话框
      proxy.$confirm({
          title: '删除提醒',
          message: `是否确认删除 ${item.product.name} ?`
      }).then(async () => {
          var params = {
              cartid: item.id,
              busid: business.value.id
          }

          var result = await proxy.$POST({url: '/cart/del', params})

          if(result.code == 0)
          {
              proxy.$fail(result.msg)
              return false
          }

          proxy.$success(result.msg)

          //删除的数据从 列表中截取出去
          CartList.value.splice(index,1);

      }).catch(err => {})
  }

  //提交订单
  const OnSubmit = () =>
  {
      if(CheckedArr.value.length <= 0)
      {
          proxy.$fail('请选择下单的商品')
          return false
      }

      proxy.$router.push({path: '/cart/confirm', query: {cartids: CheckedArr.value.join(',')}})
  }
</script>

<style scoped>
  @import url('/assets/css/cart.css');
</style>